package cn.com.jinhao.hotline.commons.util;

import cn.com.jinhao.hotline.commons.base.constant.SystemConstant;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.ToString;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Description: 响应返回基类
 *
 * @author ShaneWei
 */
@Getter
@ToString
@ApiModel(value = "RestResponse", description = "统一响应返回信息")
public class RestResponse<T> {
    /**
     * 返回码
     */
    @ApiModelProperty(value = "状态返回码", notes = "默认为200是成功")
    private Integer code;
    /**
     * 返回信息
     */
    @ApiModelProperty(value = "响应信息", notes = "来说明响应情况")
    private String message;
    /**
     * 返回数据
     */
    @ApiModelProperty(value = "响应数据", notes = "响应的具体数据")
    private T data;

    /**
     * 签名
     */
    @ApiModelProperty(value = "签名", notes = "签名信息，保证不被拦截篡改")
    private String sign;

    public RestResponse(T data) {
        this(SystemConstant.ResponseCode.SUCCESS, data);
    }

    public RestResponse(SystemConstant.ResponseCode responseCode, T data) {
        this.code = responseCode.getStatus();
        this.message = responseCode.getName();
        this.data = data;
        this.pushSign();
    }

    public RestResponse(SystemConstant.ResponseCode responseCode, T data, String message) {
        this.code = responseCode.getStatus();
        this.message = message;
        this.data = data;
        this.pushSign();
    }

    public void pushSign() {
        Map<String, String> params = new HashMap<>(10);
        params.put("code", this.code.toString());
        params.put("message", this.message);
        if (Optional.ofNullable(this.data).isPresent()) {
            params.put("data", JSON.toJSONString(this.data));
        }

        this.sign = MessageDigestUtils.encrypt(MessageDigestUtils.getSignatureStr(params) + SystemConstant.SystemConfig.SALT.getName(), Algorithm.MD5);
    }
}
